<script>
import { getglobalSettings, searchGlobalSettings, updateAllGlobalSetting } from '@/api/globalSetting'

export default {
  name: 'Index',
  data() {
    return {
      settingData: [],
      filterList: ['app_info_api', 'app_info_prompt', 'match_param_llm', 'match_param_prompt', 'planning_api', 'planning_prompt', 'rethink_api', 'rethink_prompt', 'tool_api', 'tool_prompt', 'profile_schemas']
    }
  },
  created() {
    // 加载设置项到settingData中
    this.fetchSetting()
  },
  methods: {
    async fetchSetting() {
      await searchGlobalSettings({ 'searchVal': 'model_setting' })
        .then(res => {
          const list = JSON.parse(res[0].value)
          for (let i = 0; i < list.length; i++) {
            this.filterList.push(list[i]['api'])
            this.filterList.push(list[i]['prompt'])
            this.filterList.push(list[i]['parameters'])
          }
        })
        .catch(err => {
          console.log('获取大模型设置时出错：', err)
        })
      getglobalSettings()
        .then(response => {
          const settings = response.filter(item => !this.filterList.includes(item.name)) // 去掉有单独页面的设置项
          console.log(settings)
          this.settingData = settings
        })
        .catch(err => {
          console.log('获取数据出错：', err)
        })
    },
    saveSetting() {
      const data = {}
      for (let i = 0; i < this.settingData.length; i++) {
        data[this.settingData[i].name] = this.settingData[i].value
      }
      updateAllGlobalSetting(data)
        .then((res) => {
          this.$message({
            message: this.$t('Modified_successfully'),
            type: 'success'
          })
          console.log(res)
        })
        .catch(error => {
          this.$message({
            message: this.$t('Modification_failed'),
            type: 'error'
          })
          console.log('保存信息出错', error)
        })
    }
  }
}
</script>

<template>
  <div>
    <el-row class="container-item">
      <el-form v-if="settingData.length" ref="form" label-width="auto">
        <el-form-item
          v-for="(item, index) in settingData"
          :key="index"
          :label="item.labelName"
        >
          <el-input v-model="item.value" type="textarea" :autosize="true" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveSetting">{{ $t('save') }}</el-button>
        </el-form-item>
      </el-form>
      <div v-else class="loading-placeholder">
        加载中...
      </div>
    </el-row>
  </div>
</template>

<style scoped>
.container-item{
  background-color: white;
  margin: 20px 0;
  padding: 30px;
}

.loading-placeholder {
  text-align: center;
  padding: 20px;
  font-size: 16px;
  color: #888;
}
</style>
